package cn.foolishbird.hamal.frame.config;


import cn.foolishbird.hamal.frame.constant.IsEnum;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.Date;

/**
 * Zebra
 *
 * @author: zebra
 * @date: 2018/12/17
 */
//@Component
public class MpFillConfig implements MetaObjectHandler {

    private final static String DEL_FLAG = "delFlag";

    private final static String CREATE_TIME = "createTime";

    private final static String UPDATE_TIME = "updateTime";

    /**
     * <p>
     * 重写insertFill，自定义id，createTime 字段插入的时候统一添加
     * </p>
     *
     * @param metaObject
     * @return void
     * @throws
     * @author Eric
     * @date 2019/5/6
     **/
    @Override
    public void insertFill(MetaObject metaObject) {
        Class c = metaObject.getOriginalObject().getClass();
//        id 目前是自增长
//        Field idField = ReflectUtil.getField(c, ID);
//        boolean idExist = ObjectUtil.isNotNull(idField) && (metaObject.getValue(ID) == null || (long) metaObject.getValue(ID) == ZERO);
//        if (idExist) {
//            this.setFieldValByName(ID, idService.genId(), metaObject);
//        }
        Field delFlagField = ReflectionUtils.findField(c, DEL_FLAG);
        boolean delFlagExist = null != delFlagField && metaObject.getValue(DEL_FLAG) == null;
        if (delFlagExist) {
            this.setFieldValByName(DEL_FLAG, IsEnum.FALSE.getState(), metaObject);
        }
        timeField(metaObject, CREATE_TIME);

    }

    /**
     * <p>
     * 重写更新字段方法，更新更新字段
     * </p>
     *
     * @param metaObject
     * @return void
     * @throws
     * @author Eric
     * @date 2019/5/6
     **/
    @Override
    public void updateFill(MetaObject metaObject) {
        timeField(metaObject, UPDATE_TIME);
    }

    /**
     * <p>
     * 统一set时间字段，这里createTime updateTime两个字段
     * </p>
     *
     * @param metaObject
     * @param timeField
     * @return void
     * @throws
     * @author Eric
     * @date 2019/5/6
     **/
    private void timeField(MetaObject metaObject, String timeField) {
        Class c = metaObject.getOriginalObject().getClass();
        Field time = ReflectionUtils.findField(c, timeField);
       if (null != time) {
            if (time.getType() == Date.class) {
                this.setFieldValByName(timeField, new Date(), metaObject);
            }
            if (time.getType() == Long.class || time.getType() == long.class) {
                this.setFieldValByName(timeField, System.currentTimeMillis(), metaObject);
            }
        }
    }
}
